<template>
  <div class="add-package-container">
    <el-dialog
      :title="isEdit?'修改菜品':'添加菜品'"
      :visible.sync="dialogVisible"
      width="500px"
      :before-close="dialogBeforeClose"
    >
      <el-form ref="packageData" :model="packageData" :rules="rules" label-width="100px">
        <el-form-item label="套餐名称" prop="name">
          <el-input v-model="packageData.name" prop="name" placeholder="请输入菜品名称" />
        </el-form-item>
        <el-form-item label="套餐分类" prop="categoryId">
          <el-select v-model="packageData.categoryId" prop="categoryId" placeholder="请选择套餐分类">
            <el-option
              v-for="item in packageOptions"
              :key="item.id"
              :value-key="item.id"
              :label="item.name"
              :value="item.id"
            />
          </el-select>
        </el-form-item>
        <el-form-item label="套餐价格" prop="price">
          <el-input v-model="packageData.price" prop="price" placeholder="请输入套餐价格" />
        </el-form-item>
        <el-form-item label="套餐菜品" prop="dishList">
          <div class="add-package-container-flavors">
            <el-button @click="showCasPanel">添加菜品</el-button>
            <el-table
              v-if="optionsList.length > 0"
              :data="optionsList"
              style="width: 100%"
            >
              <el-table-column
                prop="name"
                label="名称"
                align="center"
              />
              <el-table-column
                prop="price"
                label="价格"
                align="center"
                :formatter="formatterPrice"
              />
              <el-table-column label="份数" align="center" min-width="200px">
                <template slot-scope="scope">
                  <el-input-number v-model="scope.row.copies" step-strictly :min="1" :max="10" label="份数" />
                </template>
              </el-table-column>
              <el-table-column label="操作" align="center" width="150px">
                <template slot-scope="scope">
                  <el-link
                    size="mini"
                    type="danger"
                    :underline="false"
                    @click="deleteDishOption(scope.row)"
                  >删除</el-link>
                </template>
              </el-table-column>
            </el-table></div>
        </el-form-item>
        <el-form-item label="菜品图片" prop="image">
          <div>
            <el-upload
              ref="upload"
              class="upload-demo"
              action="/dev-api/common/upload"
              :auto-upload="false"
              :multiple="false"
              list-type="picture-card"
              :on-change="handleAvatarChange"
              :limit="1"
              :show-file-list="false"
              :on-remove="handleRemove"
              :on-success="uploadSuccess"
            >
              <img v-if="imageUrl" :src="imageUrl" class="avatar" :onerror="defaultImg">
            </el-upload>
          </div>
        </el-form-item>
        <el-form-item label="套餐描述" prop="description">
          <el-input v-model="packageData.description" type="textarea" placeholder="请输入套餐描述" :autosize="{minRows: 2, maxRows: 6}" resize="none" />
        </el-form-item>
      </el-form>
      <div />
      <div slot="footer">
        <el-button @click="dialogBeforeClose('packageData')">取 消</el-button>
        <el-button type="primary" @click="submitData('packageData')">确 定</el-button>
      </div>
    </el-dialog>
    <el-dialog
      v-if="addDishDialogVisible"
      title="添加菜品"
      :visible.sync="addDishDialogVisible"
      width="750px"
      :before-close="dishDialogBeforeClose"
    >
      <div />
      <div style="display:flex">
        <div class="boxOne radiusClass">
          <el-scrollbar style="height:100%">
            <div
              v-for="item1 in options"
              :key="item1.id"
              :class="activeId===item1.id ? 'active' : ''"
              class="item"
              @click="tapOne(item1)"
            >
              <p>{{ item1.name }}</p>
            </div>
          </el-scrollbar>
        </div>
        <div class="boxOne radiusClass">
          <el-scrollbar style="height:100%">
            <div
              v-for=" item in childArr"
              :key="item.id"
              :class="activeIndexChild(item)? 'active' : ''"
              class="item"
              @click="changeLabel(item)"
            >

              <p v-if="childArr.length === 0" />
              <p v-else><span>{{ item.name }}</span><span>{{ item.status?'在售':'停售' }}</span><span>￥{{ item.price/100 }}</span></p>
            </div>
          </el-scrollbar>
        </div>
        <el-card>
          <div class="card-header">菜品列表</div>
          <el-tag
            v-for="(dataItem,index) in optionsList"
            :key="dataItem.id"
            closable
            @close="handleDishListClose(index)"
          >
            菜品名称：{{ dataItem.name }}&nbsp;价格：￥{{ dataItem.price/100 }}
          </el-tag>
        </el-card>
      </div>
      <div slot="footer">
        <el-button @click="cancelSubmitData">取 消</el-button>
        <el-button type="primary" @click="addDishes">确 定</el-button>
      </div>
    </el-dialog>
  </div>
</template>

<script>
import { getCategoryList, getDishDetail } from '@/api/dish'
import { addSetMeal, editSetMeal, getSetMealById } from '@/api/package'
import { validName } from '@/utils/validate'
import { EventBus } from '@/utils/eventBus'
import { deepClone } from '@/utils/myUtil'
import { downloadImg } from '@/api/dish'
export default {
  name: 'AddPackage',
  props: {
    show: {
      type: Boolean,
      require: true,
      default: true
    },
    isEdit: {
      type: Boolean,
      require: true,
      default: false
    },
    setMealId: {
      type: String,
      require: false,
      default: ''
    }
  },
  data() {
    function validCategoryId(rule, value, callback) {
      if (!value) {
        callback(new Error('请选择套餐分类'))
      }
      callback()
    }
    function validPrice(rule, value, callback) {
      if (!value) {
        callback(new Error('请输入价格'))
      }
      const price = parseFloat(value)
      if (isNaN(price)) {
        callback(new Error('价格只能为数字'))
      } else if (price < 0) {
        callback(new Error('价格不能为负数'))
      } else if (price > 10000) {
        callback(new Error('价格只能小于10000'))
      }
      callback()
    }
    return {
      packageData: {
        name: '',
        type: '',
        price: '',
        categoryId: '',
        image: '',
        description: '',
        dishList: []
      },
      defaultImg: 'this.src="' + require('@/assets/defaultImg/noImg.png') + '"',
      imageUrl: '',
      options: [],
      packageOptions: [],
      selectedOptions: [],
      props: {
        value: 'id',
        label: 'name',
        multiple: true,
        checkStrictly: false
      },
      addDishDialogVisible: false,
      optionsList: [],
      activeId: '',
      rules: {
        name: { validator: validName, trigger: blur },
        categoryId: { validator: validCategoryId, trigger: blur },
        price: { validator: validPrice, trigger: blur }
      },
      childArr: [],
      storageOptionList: [],
      storageSelectedOptions: []
    }
  },
  computed: {
    dialogVisible: {
      get() {
        return this.show
      },
      set(val) {
        this.$emit('update:show', val)
      }
    }
  },
  watch: {
    selectedOptions: {
      deep: true,
      handler() {
        this.$forceUpdate()
      }
    }
  },
  created() {
    this.getPackageData()
    this.getOptionsData()
    if (this.isEdit) {
      console.log(this.setMealId)
      // this.packageData = deepClone(this.packageInformation)
      this.getPackageDataById(this.setMealId)
      console.log(this.packageData, '....')
    }
  },
  methods: {
    activeIndexChild(item) {
      return this.selectedOptions.findIndex((id) => id === item.id) !== -1
    },
    async getPackageDataById(id) {
      const { data } = await getSetMealById(id)
      console.log(data)
      if (data) {
        this.packageData = deepClone(data)
      }
      this.packageData.price /= 100
      this.imageUrl = downloadImg(this.packageData.image)
      const { setmealDishes } = data
      setmealDishes.price /= 100
      this.optionsList = deepClone(setmealDishes)
      this.storageOptionList = deepClone(setmealDishes)
      this.selectedOptions = []
      setmealDishes.forEach((dish) => {
        this.selectedOptions.splice(this.selectedOptions.length, 0, dish.dishId)
      })
      this.storageSelectedOptions = deepClone(this.selectedOptions)
      this.activeId = this.selectedOptions[0].id
    },
    async getPackageData() {
      const { data } = await getCategoryList({ type: 2 })
      this.packageOptions = data || []
    },
    async getOptionsData() {
      const { data } = await getCategoryList({ type: 1 })
      console.log(data)
      this.options = data || []
      if (data.length) {
        data.forEach(async(d, index) => {
          const res = await getDishDetail({ categoryId: d.id })
          if (res.data) {
            this.options[index].children = res.data || []
            if (index === 0 && res.data.length) {
              this.childArr = this.options[0].children
            }
          }
        })
      }
    },
    dialogBeforeClose() {
      this.dialogVisible = false
    },
    submitData(formName) {
      this.$refs[formName].validate(async(valid) => {
        if (valid) {
          this.packageData.price *= 100
          const { name, price, description, categoryId, image } = this.packageData
          const setmealDishes = this.optionsList
          let res
          if (this.isEdit) {
            res = await editSetMeal({ ...this.packageData, setmealDishes })
          } else {
            res = await addSetMeal({ name, price, description, categoryId, dishList: [], code: '', idType: categoryId, image, setmealDishes, status: 1 })
          }
          const { code } = res
          if (code) {
            this.$message.success(this.isEdit ? '修改成功' : '添加成功')
            EventBus.$emit('refetchPackageData')
            this.dialogBeforeClose()
          }
        } else {
          console.log('error submit!!')
          return false
        }
      })
    },
    showCasPanel() {
      this.addDishDialogVisible = true
    },
    dishDialogBeforeClose() {
      this.cancelSubmitData()
    },
    addDishes() {
      this.addDishDialogVisible = false
    },
    handleRemove(file, fileList) {
      this.imageUrl = ''
    },
    handleAvatarChange(file, fileList) {
      this.$refs.upload.submit()
    },
    uploadSuccess(res) {
      const { data } = res
      this.dishData.image = data
      this.imageUrl = downloadImg(data)
      this.packageData.image = data
    },
    changeLabel(item) {
      const index = this.selectedOptions.findIndex((id) => id === item.id)
      if (index === -1) {
        this.selectedOptions.push(item.id)
        const { price, id, name } = item
        this.optionsList.push({ name, price, dishId: id, copies: 1 })
      } else {
        this.selectedOptions.splice(index, 1)
      }
      console.log(this.selectedOptions)
    },
    handleDishListClose(index) {
      this.optionsList.splice(index, 1)
      this.selectedOptions.splice(index, 1)
      this.$forceUpdate()
    },
    cancelSubmitData() {
      this.selectedOptions = this.storageSelectedOptions
      this.optionsList = this.storageOptionList
      this.addDishDialogVisible = false
    },
    tapOne(item) {
      this.activeId = item.id
      this.childArr = item.children || []
    },
    formatterPrice(row) {
      return '￥' + (row.price / 100)
    },
    async formatterImg(name) {
      return await downloadImg({ name })
    }
  }
}
</script>

<style lang="scss">
.add-package-container{
  &-flavors{
    .el-button{
      margin: 5px auto;
    }
    &-input{
      display: flex;
      &-name{
        width: 130px;
      }

      &-tag{
        margin-left:10px;
        height: 40px;
        line-height: 40px;
        border: 1px solid #ccc;
        border-radius: 4px;
        white-space:nowrap;
        width: 430px;
        overflow: hidden;
        overflow-x: scroll;
        display: -webkit-box;

        &::-webkit-scrollbar{
          display: none;
        }
        .el-button{
          display: inline-block;
          border: 0px;
          margin: auto 5px;
        }

        .el-tag{
          display: inline-block;
          margin: 2px 5px;
        }

        .el-input{
          display: inline-block;
          width: 80px;
          .el-input__inner{
            border: 0px;
          }
        }
      }
    }
  }
  .el-cascader-panel {
    .el-scrollbar:first-child {
      .el-checkbox {
        display: none;
        margin-left:-10px;
      }
    }
  }
  .el-cascader-menu__wrap{
    height: 100%;
  }
  .el-tag{
    margin: 5px 5px;
  }
  .wrap {
    display: flex;
    padding-top: 20px;
    padding-left: 20px;
    font-size: 14px;
  }

  .item:hover {
    background-color: #eee;
    cursor: pointer;
  }

  .item {
    display: flex;
    align-items: center;
  }

  .add {
    width: calc(100% - 20px);
    position: absolute;
    bottom: 10px;
    left: 50%;
    transform: translateX(-50%);
  }

  p{
    width: 100%;
    padding: 0 30px 0 20px;
    height: 34px;
    line-height: 34px;
  }
  .boxOne,
  .boxTwo,
  .boxThree {
    height: 400px;
    padding-bottom: 30px;
    min-width: 180px;
    box-sizing: border-box;
    color: #606266;
    border: 1px solid #e4e7ed;
    border-left: none;
    position: relative;
  }

  .boxOne {
    border-top-left-radius: 5px;
    border-bottom-left-radius: 5px;
  }

  .radiusClass {
    border-top-right-radius: 5px;
    border-bottom-right-radius: 5px;
  }

  .boxOne {
    border-left: 1px solid #e4e7ed;
  }

  .active {
    color: #409eff;
    background-color: #eee;
  }

  .el-scrollbar__wrap {
    overflow-x: hidden;
  }
  .el-card{
    width: 280px;
    overflow-x: scroll;
  }
  .el-select{
    display: block;
  }
  &-upload{
    .el-upload--picture-card {
      display: none;
    }
  }
  img{
    width: 100% !important;
    height: 100% !important;
  }
}
</style>
